package com.example.xjtuse_pc.engine;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Debug;

import com.example.xjtuse_pc.domain.TaskInfo;
import com.example.xjtuse_pc.mobilesafe.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XJTUSE-PC on 2016/5/18.
 */
public class TaskInfoProvider {
    public static  List<TaskInfo> getTaskInfos(Context context) {
        List<TaskInfo> tis=new ArrayList<TaskInfo>();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = context.getPackageManager();
        java.util.List<ActivityManager.RunningAppProcessInfo> rifo = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo s : rifo) {
            TaskInfo ti=new TaskInfo();
            String packname = s.processName;
            ti.setPackname(packname);
            Debug.MemoryInfo[] mi=am.getProcessMemoryInfo(new int[]{s.pid});
            long memSize=mi[0].getTotalPrivateDirty()*1024;
                ti.setMemSize(memSize);
            try {
                ApplicationInfo ai = pm.getApplicationInfo(packname, 0);
                Drawable icon = ai.loadIcon(pm);
                ti.setIcon(icon);
                String name = ai.loadLabel(pm).toString();
                ti.setName(name);
                //ti.setCheck(false);
                if((ai.flags & ai.FLAG_SYSTEM)==0){
                    //用户进程
                    ti.setUserTask(true);
                }else {
                    //系统进程
                    ti.setUserTask(false);
                }

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                ti.setIcon(context.getResources().getDrawable(R.drawable.ic_launch));
                ti.setName(packname);
            }
            tis.add(ti);
        }
        return tis;
    }
}
